//
// Created by leisurexi on 10/4/20.
//
#include "lib/common.h"
#include <aio.h>

const int BUF_SIZE = 512;

int main() {
    int err;
    int result_size;

    char tmp_name[256];
    snprintf(tmp_name, sizeof(tmp_name), "tmp/aio_test_%d", getpid());
    unlink(tmp_name);
    int fd = open(tmp_name, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        error(1, errno, "open file failed");
    }
    unlink(tmp_name);

    char buf[BUF_SIZE];
    struct aiocb aiocb;

    memset(buf, 0xfa, BUF_SIZE);
    memset(&aiocb, 0, sizeof(struct aiocb));
    aiocb.aio_fildes = fd;
    aiocb.aio_buf = buf;
    aiocb.aio_nbytes = BUF_SIZE;

    if (aio_write(&aiocb) == -1) {
        printf("Error at aio_write(): %s\n", strerror(errno));
        close(fd);
        exit(1);
    }

    while (aio_error(&aiocb) == EINPROGRESS) {
        printf("writing... \n");
    }

    err = aio_error(&aiocb);
    result_size = aio_return(&aiocb);
    if (err != 0 || result_size != BUF_SIZE) {
        printf("aio_write failed(): %s\n", strerror(err));
        close(fd);
        exit(1);
    }

    char buffer[BUF_SIZE];
    struct aiocb cb;
    cb.aio_nbytes = BUF_SIZE;
    cb.aio_fildes = fd;
    cb.aio_offset = 0;
    cb.aio_buf = buffer;

    if (aio_read(&cb) == -1) {
        printf("aio_read failed(): %s\n", strerror(err));
        close(fd);
    }

    while (aio_error(&cb) == EINPROGRESS) {
        printf("Reading... \n");
    }

    int numBytes = aio_return(&cb);
    if (numBytes != -1) {
        printf("Success.\n");
    } else {
        printf("Error.\n");
    }

    close(fd);
    return 0;
}
